package cn.xy.base.server.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页转换工具类
 *
 * @author xy
 */
public class PageUtil {

    private PageUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * @param page    旧分页
     * @param records 分页记录列表
     * @param <T>     泛型
     * @return 指定泛型分页
     */
    public static <T> Page<T> toPage(@NotNull Page<?> page, List<T> records) {
        Page<T> newPage = new Page<>();
        newPage.setRecords(records);
        newPage.setCurrent(page.getCurrent());
        newPage.setSize(page.getSize());
        newPage.setPages(page.getPages());
        newPage.setTotal(page.getTotal());
        return newPage;
    }

    public static <T> Page<T> recordToPage(@NotNull Page<?> page, List<T> recordList) {
        List<T> newRecordList = new ArrayList<>();
        long currentPage = page.getCurrent();
        long pageSize = page.getSize();
        page.setTotal(recordList.size());
        for (long i = pageSize * (currentPage - 1), size = 0; i < recordList.size() && size < pageSize; i++, size++) {
            newRecordList.add(recordList.get((int) i));
        }
        return toPage(page, newRecordList);
    }
}

